package com.goldgov.code.template.model;

import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class OptionOutputModel implements TemplateDirectiveModel {
	
	private ObjectMapper om = new ObjectMapper();
	
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		Object optionParams = params.get("optionParams");
		Object indentParams = params.get("indent");
		Object elementParams = params.get("element");
		
		if(optionParams == null) {
			return;
		}
		
		int indent = Integer.valueOf(indentParams.toString());
		String indentStr = "";
		for (int i = 0; i < indent; i++) {
			indentStr += " ";
		}
		
		Map<String,String> readValue = om.readValue(optionParams.toString(), Map.class);
		
		Iterator<String> keyIterator = readValue.keySet().iterator();
		Writer out = env.getOut();
		while(keyIterator.hasNext()) {
			String value = keyIterator.next();
			String display = readValue.get(value);
			if(elementParams == null) {
				out.write("{\r\n" + indentStr + "  label: '" + display + "',\r\n" + indentStr + "  value: '" + value + "'\r\n" + indentStr + "}");
				if(keyIterator.hasNext()) {
					out.write(", ");
				}
			}else {
				out.write(indentStr+"<Option value=\"" + value + "\">" + display + "</Option>\r\n");
			}
			
		}
		
	}

}
